﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Furion.Models;
using System.Web.Script.Serialization;
using System.Data.SqlClient;

namespace Furion.Controllers
{
    public class HomeController : Controller
    {
        //

        public ActionResult Index()
        {
            List<Menu> menuList = Menu.GetMenuList();
            return View(menuList);
        }
       
        public ActionResult Home()
        {
            return View();
        }

        [HttpPost]
        public ActionResult GetEntities(string request)
        {
            var result = new List<AutoCompleteEnity>();
            var context = new Furion.DB_9B1C04_furionEntities1();
            var selectedPortFolios = context.tblPortfolios.Where(t => t.fldPtfCode.ToLower().Contains(request.ToLower())).Select(s => 
                new AutoCompleteEnity 
                {
                    Entity = s.fldPtfCode,
                    EntityDesc = s.fldPtfName,
                    EntityType = s.fldEntityType
                });
            var model = selectedPortFolios.ToList();
            return Json(model, JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetPortfolio()
        {
            var model = new PortfolioViewModel();
            var context = new Furion.DB_9B1C04_furionEntities1();
            var entityDropdown = new PortFolioDropDownList { 
                Id = "entityType", 
                DropDownName = "Entity Type",
                EntityDropDown = GetEntityTypes(context.tblPortfolios.ToList()).ToList()
            };
            model.DropDowns.Add(entityDropdown);
            var ccyDropdown = new PortFolioDropDownList
            { 
                Id = "currency",
                DropDownName = "Currency",
                EntityDropDown = context.tblRefCcies.Select(t => new SelectListItem { Text = t.fldCcyCode, Value = t.fldCcyID.ToString() }).ToList()
            };
            model.DropDowns.Add(ccyDropdown);
            var countryDrodown = new PortFolioDropDownList 
            { 
                Id = "country", 
                DropDownName = "Country",
                EntityDropDown = context.tblRefCountries.Select(t => new SelectListItem { Text = t.fldCountryCode, Value = t.fldCountryID.ToString() }).ToList()
            };            
            model.DropDowns.Add(countryDrodown);
            var managedByDropdown = new PortFolioDropDownList 
            { 
                Id = "managedBy", 
                DropDownName = "Managed By",
                EntityDropDown = context.tblRefFundMgrs.Select(t => new SelectListItem { Text = t.fldFirstName + " " + t.fldLastName, Value = t.fldFundMgrID.ToString() }).ToList()
            };
            model.DropDowns.Add(managedByDropdown);
            var invDeskDropdown = new PortFolioDropDownList 
            { 
                Id = "investmentDesk", 
                DropDownName = "Investment Desk",
                EntityDropDown = context.tblRefInvDesks.Select(t => new SelectListItem { Text = t.fldInvDeskCode, Value = t.fldInvDeskID.ToString() }).ToList()
            };
            model.DropDowns.Add(invDeskDropdown);
            var assetClassDropDown = new PortFolioDropDownList 
            { 
                Id = "assetClass", 
                DropDownName = "Asset Class",
                EntityDropDown = context.tblRefAssetClasses.Select(t => new SelectListItem { Text = t.fldAssetClassCode, Value = t.fldAssetClassID.ToString() }).ToList()
            };            
            model.DropDowns.Add(assetClassDropDown);
            var dataLoadDropdown = new PortFolioDropDownList
            {
                Id = "dataLoadType",
                DropDownName = "Data Load Type",
                EntityDropDown = context.tblRefDataLoadTypes.Select(t => new SelectListItem { Text = t.fldDataLoadTypeCode, Value = t.fldDataLoadTypeID.ToString() }).ToList()
            };
            model.DropDowns.Add(dataLoadDropdown);
            model.DropDowns.Add(new PortFolioDropDownList { Id = "partOfGroup", DropDownName = "Part of Group", EntityDropDown = new List<SelectListItem>() });
            return PartialView("_Portfolio",model);
        }

        public ActionResult GetGriData(EntitySearchCriteria criteria)
        {
            var model = new List<EntityGrid>();
            var portfolios = GetPortFolios(criteria);
            model = GetEntityGridData(portfolios);
            return Json(model, JsonRequestBehavior.AllowGet);
        }

        public ActionResult SearchPortfolio(EntitySearchCriteria criteria)
        {
            var data = new List<EntityGrid>();
            var portfolios = GetPortFolios(criteria);
            data = GetEntityGridData(portfolios);
            return Json(data,JsonRequestBehavior.AllowGet);
        }

        public ActionResult CreatePortFolio()
        {
            var model = new CreatePortfolioViewModel();
            var context = new DB_9B1C04_furionEntities1();
            model.AssetClassList = context.tblRefAssetClasses.Select(t => new SelectListItem { Text=t.fldAssetClassCode,Value=t.fldAssetClassID.ToString() }).ToList();
            model.CountryList = context.tblRefCountries.Select(t => new SelectListItem { Text = t.fldCountryName, Value = t.fldCountryID.ToString() }).ToList();
            model.CurrencyList = context.tblRefCcies.Select(t => new SelectListItem { Text = t.fldCcyCode, Value = t.fldCcyID.ToString() }).ToList();
            model.FundManagerList = context.tblRefFundMgrs.Select(t => new SelectListItem { Text = t.fldFirstName + " "+t.fldLastName, Value = t.fldFundMgrID.ToString() }).ToList();
            model.InvestmentDeskList = context.tblRefInvDesks.Select(t => new SelectListItem { Text = t.fldInvDeskName, Value = t.fldInvDeskID.ToString() }).ToList();
            model.DataLoadTypeList = context.tblRefDataLoadTypes.Select(t => new SelectListItem { Text = t.fldDataLoadTypeName, Value = t.fldDataLoadTypeID.ToString() }).ToList();
            model.BenchmarkList = context.tblCharacBmks.Select(t => new SelectListItem { Text = t.fldBmkName, Value = t.fldBmkID.ToString() }).ToList();
            model.portfolioCheck = false;
            model.PortfolioType = "Sub-Portfolio";
            return PartialView("_CreatePortfolio", model);
        }

        public ActionResult AddPortfolio(string portfolio)
        {
            var returnValue = new ReturnValue();
            var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            var portfolioEntity = serializer.Deserialize<CreatePortfolioViewModel>(portfolio);
            if (portfolioEntity != null)
            {
                var newPortfolio = new tblPortfolio 
                { 
                    fldPtfName = portfolioEntity.Name,
                    fldLaunchDate = (DateTime)portfolioEntity.StartDate,
                    fldAssetClassID = (int)portfolioEntity.AssetClass,
                    fldCcyID = (int)portfolioEntity.Currency,
                    fldCountryID = (int)portfolioEntity.Country,
                    fldDataLoadTypeID = (int)portfolioEntity.DataLoadType,
                    fldEntityType = portfolioEntity.PortfolioType,
                    fldFundMgrID = (int)portfolioEntity.FundManager,
                    fldInvDeskID = (int)portfolioEntity.InvestmentDesk,
                    fldOPTarg = (decimal)portfolioEntity.OutputTarget,
                    fldPtfCode = portfolioEntity.Code,
                    fldIsActive = true,
                    fldCloseDate = null,
                    fldApprovedDate = null

                };
                if(portfolioEntity.portfolioCheck)
                {
                    newPortfolio.fldEntityType = "Sub-Portfolio";
                    
                    var context = new DB_9B1C04_furionEntities1();
                    try
                    {
                        context.tblPortfolios.Add(newPortfolio);
                        context.SaveChanges();
                        returnValue.Success = true;
                        returnValue.Message = "Portfolio created successfully";
                    }
                    catch(Exception ex)
                    {
                        returnValue.Success = false;
                        returnValue.Message = "Error occured. please contact adminstrator";
                    }

                }
                
            }
            return Json(returnValue, JsonRequestBehavior.AllowGet);
        }

        public ActionResult UserResponse(string message)
        {
            ViewBag.Message = message;
            return PartialView("_UserResponse");
        }
        private List<tblPortfolio> GetPortFolios(EntitySearchCriteria criteria)
        {
            
            var context = new DB_9B1C04_furionEntities1();
            var portfolios = context.uspSearchPortFolio(criteria.EntityType, criteria.Currency, criteria.Country, 
                                                            criteria.ManagedBy, criteria.InvestmentDesk, criteria.DataLoad, 
                                                            criteria.ApprovedDate, criteria.LatestData);
            return portfolios.ToList();
        }

        private List<SelectListItem> GetEntityTypes(List<tblPortfolio> portfolios)
        {
            var entityTypes = new List<SelectListItem>();
            if(portfolios != null)
            {
                foreach(var portfolio in portfolios)
                {
                    if(!entityTypes.Any(t=>t.Text == portfolio.fldEntityType))
                    {
                        entityTypes.Add(new SelectListItem { Text = portfolio.fldEntityType, Value = portfolio.fldEntityType });
                    }
                }
            }
            return entityTypes;
        }

        private List<EntityGrid> GetEntityGridData(List<tblPortfolio> portfolios)
        {
            var data = new List<EntityGrid>();
            if(portfolios != null)
            {
                data = portfolios.Select(t => new EntityGrid
                {
                    portfolioId = t.fldPtfID,
                    EntityType = t.fldEntityType,
                    Name = t.fldPtfName,
                    Code = t.fldPtfCode,
                    Currency = t.tblRefCcy != null ?  t.tblRefCcy.fldCcyCode:"",
                    FundManager = t.tblRefFundMgr != null ?  t.tblRefFundMgr.fldFirstName + " " + t.tblRefFundMgr.fldLastName:"",
                    InvestmentDesk = t.tblRefInvDesk != null ?  t.tblRefInvDesk.fldInvDeskName : "",
                    DataLoad = t.tblRefDataLoadType != null ? t.tblRefDataLoadType.fldDataLoadTypeName:"",
                    ApprovedDate = t.fldApprovedDate.ToString(),
                    AssetClass = t.tblRefAssetClass != null ? t.tblRefAssetClass.fldAssetClassName:"",
                    Country = t.tblRefCountry != null ? t.tblRefCountry.fldCountryName :""
                }).ToList();
            }
            return data;
        }
	}
}